package com.shangan.shortlink.admin.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangan.shortlink.admin.common.convention.exception.ClientException;
import com.shangan.shortlink.admin.common.enums.UserErrorCodeNum;
import com.shangan.shortlink.admin.dao.entity.UserDO;
import com.shangan.shortlink.admin.dao.mapper.UserMapper;
import com.shangan.shortlink.admin.dto.req.UserLoginReqDTO;
import com.shangan.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.shangan.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.shangan.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.shangan.shortlink.admin.dto.resp.UserRespDTO;
import com.shangan.shortlink.admin.service.UserService;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.shangan.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;

/**
 * @author: Jerryzaj
 * @description TODO
 * @date: 2024/4/27 16:44
 */

/**
 * 用户接口实现层
 */

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private static final long LOCK_ACQUIRE_TIMEOUT = 60;
    private static final long LOCK_WAIT_TIME = 60;

    private final RBloomFilter<String> rBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO one = baseMapper.selectOne(wrapper);
        if (one==null){
            System.out.println(one);
            throw new ClientException(UserErrorCodeNum.USER_NULL);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(one,userRespDTO);
        return userRespDTO;
    }

    @Override
    public Boolean hasUsername(String username) {
//        LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
//                .eq(UserDO::getUsername, username);
//        UserDO one = baseMapper.selectOne(wrapper);
//        if (one==null){
//            System.out.println(one);
//            throw new ClientException(UserErrorCodeNum.USER_NULL);
//        }
//        //return one.equals(null);
//        return one==null;
        return !rBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(!hasUsername(requestParam.getUsername())){
            throw new ClientException(UserErrorCodeNum.USER_NAME_EXIST);
        }
        boolean locked = false;
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());

//        try {
//            locked = lock.tryLock(LOCK_ACQUIRE_TIMEOUT, LOCK_WAIT_TIME, TimeUnit.MILLISECONDS);
//            if (!locked){
//                // 无法获取锁，可能是用户名正在被其他线程注册，或者其他系统问题
//                throw new ClientException(UserErrorCodeNum.LOCK_ACQUISITION_FAILED);
//            }
//            // 插入用户数据到数据库
//            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
//            if(insert<1){
//                throw new ClientException(UserErrorCodeNum.USER_SAVE_ERROR);
//            }
//            rBloomFilter.add(requestParam.getUsername());
//            return;
//        }catch (InterruptedException e){
//            // 处理中断异常，可能是在等待锁时被中断
//            Thread.currentThread().interrupt(); // 恢复中断状态
//            throw new ClientException(UserErrorCodeNum.USER_NAME_EXIST);
//        } finally {
//            // 无论如何，最后都要释放锁
//            if (locked) {
//                try {
//                    lock.unlock();
//                } catch (Exception ex) {
//                    // 处理解锁异常
//                    log.error("Unlock failed for lock: " + lock, ex);
//                    // 这里可以决定是否要抛出异常或记录日志后继续
//                }
//            }
//        }
        if(!lock.tryLock()){
            throw new ClientException(UserErrorCodeNum.USER_NAME_EXIST);
        }
        try {
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if(insert<1){
                throw new ClientException(UserErrorCodeNum.USER_SAVE_ERROR);
            }
            rBloomFilter.add(requestParam.getUsername());
        }finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        // TODO验证当前用户是否为登录用户
        LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), wrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class)
                        .eq(UserDO::getUsername, requestParam.getUsername())
                        .eq(UserDO::getPassword, requestParam.getPassword())
                        .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(wrapper);
        /**
         * 存在问题，可以一直请求登录接口，每一次会生成新的token，这样肯定不行
         */
        if (userDO == null){
            throw new ClientException("用户不存在");
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_"+ requestParam.getUsername());
        if (hasLogin!=null && hasLogin){
            throw new ClientException("用户已登录");
        }
        /**
         * key：login_username
         * hashkey：uuid
         * hashvalue：JSON.toJSONString(userDO)
         */
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(uuid, JSON.toJSONString(userDO), 30L, TimeUnit.MINUTES);


        stringRedisTemplate.opsForHash().put("login_"+ requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_"+ requestParam.getUsername(), 30L, TimeUnit.MINUTES);

        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username, token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)){
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户token不存在或用户不存在");
    }
}
